﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace Codeplus.Library.Web
{
    public class CustomRequest
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] GetPostData(IDictionary<string, string> data)
        {
            if (data == null) throw new ArgumentException("Data dictionary is null");
            if (data.Count == 0) throw new ArgumentException("Data dictionary is empty");

            var iterator = data.GetEnumerator();
            var dataBuilder = new StringBuilder();
            while (iterator.MoveNext())
            {
                var current = iterator.Current;
                dataBuilder.AppendFormat("&{0}={1}", current.Key, current.Value);
            }
            return Encoding.UTF8.GetBytes(dataBuilder.ToString().TrimStart("&".ToCharArray()));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public string MakeWebRequest(string url, byte[] postData)
        {
            try
            {
                var request = WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                var requestStream = request.GetRequestStream();
                using (requestStream)
                {
                    requestStream.Write(postData, 0, postData.Length);
                }
                var response = request.GetResponse();
                if (response != null)
                {
                    var responseStream = response.GetResponseStream();
                    if (responseStream != null)
                    {
                        using (var responseReader = new StreamReader(responseStream))
                        {
                            return responseReader.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new CustomRequestFailedException(ex.Message, ex);
            }
            return null;
        }
    }
}
